#include "energydashboard.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QSplitter>
#include <QGroupBox>
#include <QFormLayout>
#include <QRandomGenerator>
#include <QPushButton>
#include <QHeaderView>
#include <QBarCategoryAxis>
#include <QBarSeries>
#include <QBarSet>
#include <QValueAxis>
#include <QLineSeries>
// #include <QLineA

EnergyDashboard::EnergyDashboard(QWidget *parent)
    : QWidget{parent}
{
    setupUI();
    loadSampleData();
    setupConnections();
}

void EnergyDashboard::setupUI() {
    QHBoxLayout *mainLayout = new QHBoxLayout(this);
    // 左侧控制面板
    QWidget *controlPanel = createControlPanel();
    mainLayout->addWidget(controlPanel, 1);

    // 右侧可视化区域
    QTabWidget *visualTabs = new QTabWidget;
    visualTabs->addTab(createChartTab(), "图表分析");
    visualTabs->addTab(createDataTab(), "原始数据");
    mainLayout->addWidget(visualTabs, 3);

    setStyleSheet("QWidget { background: #f5f6fa; }"
                  "QGroupBox { border: 1px solid #dcdde1; margin-top: 10px; }"
                  "QPushButton { padding: 8px; background: #487eb0; color: white; }");
}

QWidget* EnergyDashboard::createControlPanel() {
    QWidget *panel = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(panel);

    // 数据筛选
    QGroupBox *filterGroup = new QGroupBox("数据筛选");
    QFormLayout *filterLayout = new QFormLayout(filterGroup);

    dateFrom = new QDateEdit(QDate::currentDate().addDays(-7));
    dateTo = new QDateEdit(QDate::currentDate());
    categoryCombo = new QComboBox;
    categoryCombo->addItems({"全部设备", "采集器1", "采集器2", "采集器3", "采集器4"});

    filterLayout->addRow("开始日期:", dateFrom);
    filterLayout->addRow("结束日期:", dateTo);
    filterLayout->addRow("设备筛选:", categoryCombo);

    // 分析类型
    QGroupBox *analysisGroup = new QGroupBox("分析维度");
    QVBoxLayout *analysisLayout = new QVBoxLayout(analysisGroup);

    dimensionCombo = new QComboBox;
    dimensionCombo->addItems({"按日期", "按类别", "按能耗区间"});
    analysisLayout->addWidget(dimensionCombo);

    analyzeBtn = new QPushButton("执行分析");
    analysisLayout->addWidget(analyzeBtn);
    connect(analyzeBtn,SIGNAL(pressed()),this,SLOT(analyze_data()));
    layout->addWidget(filterGroup);
    layout->addWidget(analysisGroup);
    layout->addStretch();

    return panel;
}

QWidget* EnergyDashboard::createChartTab() {
    QWidget *tab = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(tab);

    // 统计摘要
    QHBoxLayout *summaryLayout = new QHBoxLayout;
    lblTotalSales = createSummaryLabel("总能耗", "0KWH", "#2ecc71");
    lblAvgPrice = createSummaryLabel("平均能耗", "0KWH", "#3498db");
    lblTopCategory = createSummaryLabel("碳排放量", "TN/A", "#e74c3c");

    summaryLayout->addWidget(lblTotalSales);
    summaryLayout->addWidget(lblAvgPrice);
    summaryLayout->addWidget(lblTopCategory);
    layout->addLayout(summaryLayout);

    // 图表区
    QSplitter *chartSplitter = new QSplitter(Qt::Vertical);

    mainChart = new QChartView;
    mainChart->setRenderHint(QPainter::Antialiasing);

    secondaryChart = new QChartView;
    secondaryChart->setRenderHint(QPainter::Antialiasing);

    chartSplitter->addWidget(mainChart);
    chartSplitter->addWidget(secondaryChart);
    layout->addWidget(chartSplitter);

    return tab;
}

QWidget* EnergyDashboard::createDataTab() {
    QWidget *tab = new QWidget;
    QVBoxLayout *layout = new QVBoxLayout(tab);

    dataTable = new QTableWidget;
    dataTable->setColumnCount(5);
    dataTable->setHorizontalHeaderLabels({"日期", "类别", "瞬时能耗", "持续时间", "总能耗"});
    dataTable->horizontalHeader()->setSectionResizeMode(QHeaderView::Stretch);

    QPushButton *exportBtn = new QPushButton("导出CSV");
    layout->addWidget(dataTable);
    layout->addWidget(exportBtn);

    return tab;
}

QLabel* EnergyDashboard::createSummaryLabel(const QString &title, const QString &value, const QString &color) {
    QLabel *label = new QLabel;
    label->setAlignment(Qt::AlignCenter);
    label->setStyleSheet(QString(
                             "QLabel {"
                             "  background: %1;"
                             "  border-radius: 8px;"
                             "  padding: 12px;"
                             "  color: white;"
                             "  font: bold 14px;"
                             "}").arg(color));
    label->setText(QString("<b>%1</b><br>%2").arg(title, value));
    return label;
}

void EnergyDashboard::loadSampleData() {
    // 生成示例数据
    QVector<QVector<QVariant>> sampleData;
    QStringList categories = {"电子产品", "电能耗", "水能耗", "其他能耗"};

    for(int i=0; i<100; ++i){
        QVector<QVariant> row;
        row << QDate::currentDate().addDays(-QRandomGenerator::global()->bounded(7))
            << categories[QRandomGenerator::global()->bounded(4)]
            << QRandomGenerator::global()->bounded(50, 500)
            << QRandomGenerator::global()->bounded(1, 20)
            << 0; // 占位
        row[4] = row[2].toDouble() * row[3].toDouble();
        sampleData.append(row);
    }

    // 填充表格
    dataTable->setRowCount(sampleData.size());
    for(int i=0; i<sampleData.size(); ++i){
        for(int j=0; j<5; ++j){
            dataTable->setItem(i, j, new QTableWidgetItem(sampleData[i][j].toString()));
        }
    }

    updateCharts();
}

void EnergyDashboard::updateCharts() {
    // 主图表（柱状图）
    QBarSeries *barSeries = new QBarSeries;
    QBarSet *salesSet = new QBarSet("总能耗量");
    *salesSet << 15000 << 23000 << 18400 << 26800 << 19200;
    barSeries->append(salesSet);

    barChart = new QChart;
    barChart->addSeries(barSeries);
    barChart->setTitle("各设备采集到的能耗对比");
    barChart->setAnimationOptions(QChart::SeriesAnimations);

    QStringList categories = {"采集设备1", "采集设备2", "采集设备3", "采集设备4"};
    QBarCategoryAxis *axisX = new QBarCategoryAxis;
    axisX->append(categories);
    barChart->addAxis(axisX, Qt::AlignBottom);
    barSeries->attachAxis(axisX);

    QValueAxis *axisY = new QValueAxis;
    axisY->setLabelFormat("￥%d");
    barChart->addAxis(axisY, Qt::AlignLeft);
    barSeries->attachAxis(axisY);

    mainChart->setChart(barChart);

    // 副图表（折线图）
    QLineSeries *trendSeries = new QLineSeries;
    trendSeries->setName("能耗趋势");
    for(int i=0; i<7; ++i){
        trendSeries->append(i, QRandomGenerator::global()->bounded(1000, 5000));
    }

    QChart *lineChart = new QChart;
    lineChart->addSeries(trendSeries);
    lineChart->createDefaultAxes();
    lineChart->setTitle("能耗趋势");
    secondaryChart->setChart(lineChart);

    // 更新统计摘要
    lblTotalSales->setText(QString("<b>总能耗</b><br>%1KWH").arg(78500));
    lblAvgPrice->setText(QString("<b>平均能耗</b><br>%1KWH").arg(256));
    lblTopCategory->setText(QString("<b>耗电最高设备</b><br>采集设备4"));
}

//建立连接
void EnergyDashboard::setupConnections() {
    // 连接分析按钮
    connect(findChild<QPushButton*>("analyzeBtn"), &QPushButton::clicked,
            this, &EnergyDashboard::updateCharts);

    // 连接导出按钮
    connect(findChild<QPushButton*>("exportBtn"), &QPushButton::clicked, [this](){
        // 实现导出逻辑
    });
}

//开始数据分析
void EnergyDashboard::analyze_data()
{
    if(serial_tool_widget==nullptr){qDebug()<<"EnergyDashboard类（数据分析页面）的成员serial_tool_widget为空指针";return;}
    //从数据库从筛选出这些数据，并执行计算
    //根据数据库和数据处理器来进行周期性的数据统计
    DatabaseManager &instance=DatabaseManager::instance();
    QBarSeries *barSeries = new QBarSeries;
    QBarSet *salesSet = new QBarSet("总能耗量");
    for(int device_index=0;device_index<this->serial_tool_widget->receive_processor_list->count();device_index++)
    {
        QString table_name;
        table_name+=this->serial_tool_widget->receive_processor_list->value(device_index)->address;
        // 2. 计算时间范围
        QDateTime endTime = dateTo->dateTime();
        QDateTime startTime=dateFrom->dateTime();

        // endTime=startTime;
        //获取向前一小时的时间
        QString time_forward=startTime.toString("yyyy-MM-dd HH:mm:ss");
        time_forward='\"'+time_forward;
        time_forward+='\"';
        QString time_end=endTime.toString("yyyy-MM-dd HH:mm:ss");
        time_end='\"'+time_end;
        time_end+='\"';

        // qDebug()<<"起始时间"<<time_forward;
        // qDebug()<<"结束时间"<<time_end;
        double total=0.0;
        QSqlQuery *query_range;
        QString select_range="SELECT Active_Power_ALL FROM \""+table_name
                               +"\" WHERE Recorded_Time BETWEEN "
                               +time_forward+" AND "+time_end;
        qDebug()<<select_range;
        query_range=instance.executeQuery(select_range);
        // qDebug()<<"返回结果"<<query_range->value("Apparent_Power_ALL");
        // 4. 累加结果
        double count=0;
        while (query_range->next()) {
            // bool ok;
            double value = query_range->value(0).toDouble();
            // qDebug()<<"返回结果"<<query_range->value(0).toDouble();
            total += value;
            count++;
        }
        if(count!=0)
        {
            //这一个小时有有效数据
            double result=total*0.000000278;
            result=abs(result);
            qDebug()<<"计算的结果为:"<<result;
        }
        qDebug()<<"计算的结果为:"<<count;

        *salesSet << count;


    }
    barChart->removeAllSeries();
    barSeries->append(salesSet);

}
